package com.examples.ry.layouts;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

/***
 * The problem is that in order for a control to wrap, a width other than
 * SWT.DEFAULT must be specified. This comes from the fact that a control that
 * can wrap does so only when there is insufficient space available. A further
 * problem is that in general, a layout has no idea which controls can wrap and
 * when it is appropriate to substitute a width value for SWT.DEFAULT.
 * 
 * @author ryada9
 * 
 */
public class WrapControls {
	public static void main(String[] args) {
		Display display = new Display();
		final Shell shell = new Shell(display);
		GridLayout layout = new GridLayout();
		layout.numColumns = 2;
		shell.setLayout(layout);
		Label label = new Label(shell, SWT.WRAP);
		final GridData labelData = new GridData();
		labelData.horizontalSpan = 2;
		labelData.horizontalAlignment = SWT.FILL;
		Rectangle rect = shell.getMonitor().getClientArea();
		labelData.widthHint = rect.width / 4;
		label.setLayoutData(labelData);
		label.setText("This is lots of nice text that really "
				+ "should wrap but does not. Is this a bug?");
		int style = SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL;
		final List list = new List(shell, style);
		list.setItems(new String[] { "A", "B", "C", "D" });
		GridData listData = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
		list.setLayoutData(listData);
		Button okButton = new Button(shell, SWT.PUSH);
		okButton.setText("Ok");
		Button cancelButton = new Button(shell, SWT.PUSH);
		cancelButton.setText("Cancel");
		shell.pack();
		shell.open();
		/* Adjust the width hint when the list resizes */
		list.addListener(SWT.Resize, new Listener() {
			public void handleEvent(Event event) {
				Rectangle bounds = list.getBounds();
				labelData.widthHint = bounds.width;
				shell.layout();
			}
		});
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}

}
